package ar.edu.itba.pod.legajo48013.event;

import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.HashSet;
import java.util.Set;

import ar.edu.itba.node.Node;
import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.node.api.ClusterAdministration;
import ar.edu.itba.pod.legajo48013.host.Host;
import ar.edu.itba.pod.legajo48013.rmi.LookupUtil;

public class DisconnectThread extends Thread implements Remote{

	private Host host;
	NodeInformation nodeToDisconnect;
	
	public DisconnectThread(Host host, NodeInformation node) {
		this.host = host;
		this.nodeToDisconnect = node;
	}
	
	@Override
	public void run() {
		System.out.println("disconnected in");
		try{
			
			//TODO llamar a MI disconnect en vez de todo esto
			Set<NodeInformation> nodesConnected = host.getCluster().connectedNodes();
			Set<NodeInformation> copyNodesConnected = new HashSet<NodeInformation>();
			synchronized (nodesConnected) {
				nodesConnected.remove(nodeToDisconnect);
				copyNodesConnected.addAll(nodesConnected);
			}
			for(NodeInformation n: copyNodesConnected){
				ClusterAdministration cluster = (ClusterAdministration ) LookupUtil.lookup(host, n, Node.CLUSTER_COMUNICATION);
				if( cluster != null ){
					try {
						cluster.disconnectFromGroup(nodeToDisconnect);
					} catch (NotBoundException e) {
						e.printStackTrace();
						// TODO Disconnect?? de que?
					}
				}
			}
		}catch (RemoteException e) {
			// TODO: handle exception
		}
	}

}
